import sys
import time
import logging
import struct
import threading
from smap.driver import SmapDriver
from smap.loader import SmapLoadError
from smap.util import periodicSequentialCall
import kinterbasdb
import datetime, calendar
from twisted.internet import threads, reactor

class VigilentLiveDriver(SmapDriver):
    def setup(self, opts):
        #create all the data streams (m1c1, m1c2, m2c1, m2c2, etc)
        self.ids = {}
        self.calibrations = {}
        for motename in xrange(1, 56):
            t1 = self.add_timeseries('/m%i/c1' % motename, opts.get('units_m%ic1' % motename, 'F'), data_type="double")
            t2 = self.add_timeseries('/m%i/c2' % motename, opts.get('units_m%ic2' % motename, 'F'), data_type="double")
            self.ids[motename] = (t1['uuid'], t2['uuid'])
            calFactor1 = float(opts.get("calFactor_m%ic1" % motename, '1'))
            calConstant1 = float(opts.get("calConstant_m%ic1" % motename, '0'))
            calFactor2 = float(opts.get("calFactor_m%ic2" % motename, '1'))
            calConstant2 = float(opts.get("calConstant_m%ic2" % motename, '0'))
            self.calibrations[motename] = (calFactor1, calConstant1, calFactor2, calConstant2)
        self.period = opts.get("Period", 20)
            
    def read(self):
        self.con = kinterbasdb.connect (host = 'localhost', user = 'sysdba', password = 'fcllc00', database = '/var/FederspielControls/facsdb.fdb')
        self.cursor = self.con.cursor()        
        self.cursor.execute ("SELECT name,A1,A2,datetime_stamp FROM new_data join motes on new_data.mac = motes.mac;")
        data = self.cursor.fetchall()
        for row in data:
            motename = int(row[0])
            channel1 = row[1]
            channel2 = row[2]
            motetime = calendar.timegm(row[3].utctimetuple())
            #print channel1*self.calibrations[motename][0]+self.calibrations[motename][1]
            self.add(self.ids[motename][0], motetime, channel1*self.calibrations[motename][0]+self.calibrations[motename][1])
            self.add(self.ids[motename][1], motetime, channel2*self.calibrations[motename][2]+self.calibrations[motename][3])
        self.cursor.close()

    def start(self):
        periodicSequentialCall(self.read).start(self.period)
